package com.evil.common.es.dto;

import cn.hutool.core.util.StrUtil;
import com.evil.common.core.util.StreamUtil;
import com.evil.common.es.enums.DimensionEnum;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 聚合树
 *
 * @author liyang
 * @date 2024-08-01 14:35
 */
@Data
public class AggTreeResult implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    private DimensionEnum dimensionEnum;

    private String title;

    private Object value;

    private List<AggTreeResult> children;

    public AggTreeResult() {
        this.children = new ArrayList<>();
    }

    public AggTreeResult(String title) {
        this.title = title;
        this.children = new ArrayList<>();
    }

    public AggTreeResult(String title, Object value) {
        this.title = title;
        this.value = value;
        this.children = new ArrayList<>();
    }

    public AggTreeResult(DimensionEnum dimensionEnum, String title, Object value) {
        this.dimensionEnum = dimensionEnum;
        this.title = title;
        this.value = value;
        this.children = new ArrayList<>();
    }

    public AggTreeResult(AggTreeParam<?> param, String title, Object value) {
        this.dimensionEnum = param.calDimension(title);
        this.title = title;
        this.value = value;
        this.children = new ArrayList<>();
    }

    public void addChildren(AggTreeResult aggTree) {
        this.children.add(aggTree);
    }

    /**
     * 补全子级
     */
    public void completion(Collection<String> allKeys, DimensionEnum dimensionEnum, String title, Map<String, AggTreeResult> childrenMap) {
        this.children = StreamUtil.transListT(allKeys, key -> {
            if (childrenMap.containsKey(key)) {
                return childrenMap.get(key);
            } else {
                boolean target = DimensionEnum.TARGET == dimensionEnum;
                return new AggTreeResult(dimensionEnum, target ? key : title, target ? null : key);
            }
        });
    }
}
